// 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    if (n === 1) return [1];
    let result = Array.from({length: n}).map(() => new Array(n)); ///创建二维数组
    let loop = Math.floor(n / 2);
    let i = 1;
    let startX = startY = 0;
    let count = 1;
    while(i <= loop) {
        let row = startX;
        let col = startY;
        while(col < n - i) {
            result[row][col++] = count++;
        }
        while(row < n - i) {
            result[row++][col] = count++;
        }
        while(col > startY) {
            result[row][col--] = count++;
        }
        while(row > startX) {
            result[row--][col] = count++;
        }
        startX++;
        startY++;
        i++;
    }
    if (n % 2 !== 0) {
        result[startX][startY] = count;
    }
    return result;
};
console.log(generateMatrix(4));